//
//  PersonCenterViewController.m
//  GBKTrade
//
//  Created by Shizi on 2018/6/7.
//  Copyright © 2018年 LionIT. All rights reserved.
//

#import "GSPersonViewController.h"
#import "SZPersonCenterHeadView.h"
#import "GSPersonInfoCell.h"
#import "YQPersonInformationModel.h"
#import "GSUserInfoViewController.h"
#import "AboutUsCtl.h"
#import "YQSystemAnnounceVC.h"
#import "YQMyPassCardVC.h"
#import "YQMyWalletVC.h"
#import "YQLoginVC.h"
#import "GFNavigationController.h"

@interface GSPersonViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong)  SZPersonCenterHeadView* headerView;
@property (nonatomic, copy) NSArray *dataArr;
@property (nonatomic, copy) NSArray *imagesArr;
@property (nonatomic, strong) UIButton *loginOutBtn;

//实名认证
@property (nonatomic, copy) NSString *anthStatus;

@end

@implementation GSPersonViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (KUserSingleton.bIsLogin == YES) {
        [self loadHeadData];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.headView setHidden:YES];
    self.dataArr=@[
                   @[NSLocalizedString(@"我的钱包", nil),NSLocalizedString(@"我的积分", nil)],
                   @[NSLocalizedString(@"系统公告", nil),NSLocalizedString(@"联系我们", nil)]];
//,@"friend"

    self.imagesArr=@[
                     @[@"me_wallet",@"me_tz"],
                     @[@"system",@"we"]];
    
    [self.view addSubview:self.headerView];
    if (KUserSingleton.bIsLogin == YES) {
        self.loginOutBtn.hidden = NO;
    }
    
    [self tableView];
}

- (void)loadHeadData {
    [LCProgressHUD showLoading:@""];
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"users/profile") appendParameters:nil successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            [LCProgressHUD hide];
            YQPersonInformationModel *model = [YQPersonInformationModel sharedYQPersonInformationModel];
            [model mj_setKeyValues:base.data];
            self.anthStatus = model.authStatus;
            [self.headerView.headBtn sd_setImageWithURL:[NSURL URLWithString:model.avatar] forState:UIControlStateNormal placeholderImage:YQ_IMAGE(@"header_icon")];
            self.headerView.nickNameLab.text = model.nickName;
            self.headerView.phoneNumLab.text = model.phoneNum;
            
            //开发同事注意：个人资料页面未实名认证、未设置交易密码、未添加收货地址、未添加付款与收款时，该处会一直显示“待完善”
            
            if ([model.isPaymentWay boolValue] == true
                && [model.isTradePassword boolValue] == true
                && [model.isSetAddress boolValue] == true
                && [model.authStatus integerValue] == 3) {
                self.headerView.authStatusLab.text = @"";
            }else {
                self.headerView.authStatusLab.text = @"待完善";
            }
            
        }else {
            [LCProgressHUD hide];
        }
        [self.tableView reloadData];
    } failureBlock:^(NSError *error) {
        
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_headerView.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(_headerView.frame)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionHeaderHeight = FIT(15);
        _tableView.sectionFooterHeight = FIT(0);
        [_tableView registerClass:[GSPersonInfoCell class] forCellReuseIdentifier:GSPersonInfoCellReuseIdentifier];
//        _tableView.tableHeaderView = [self tableHeaderView];
        [self.view addSubview:_tableView];
        
    }
    return _tableView;
}

- (SZPersonCenterHeadView *)headerView {
    if (!_headerView) {
        _headerView = [[SZPersonCenterHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, FIT(155))];
        WeakSelf(self);
        _headerView.selectBlock = ^{
            if (KUserSingleton.bIsLogin == YES) {
                [weakSelf.navigationController pushViewController:[GSUserInfoViewController new] animated:YES];
            }else {
                YQLoginVC* loginVC = [[YQLoginVC alloc]init];
                GFNavigationController * loginNav = [[GFNavigationController alloc] initWithRootViewController:loginVC];
                [self presentViewController:loginNav animated:YES completion:^{
                    
                }];
            }
            
        };
    }
    return _headerView;
}

- (UIButton *)loginOutBtn {
    if (!_loginOutBtn) {
        _loginOutBtn = [YQViewFactory buttonWithTitle:@"退出登录" titleColor:MainRedTextColor fontSize:kNormalButtonFont userBold:NO target:self sel:@selector(loginOutAction)];
        _loginOutBtn.backgroundColor = WhiteColor;
        _loginOutBtn.hidden = YES;
    }
    return _loginOutBtn;
}

- (void)loginOutAction {
    //退出登录
    [LCProgressHUD showLoading:@"退出登录中..."];
    NSString *urlStr = [NSString stringWithFormat:@"%@users/logout",BaseHttpUrl];
    [SZHTTPSReqManager get:urlStr appendParameters:nil successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            //清除存储的token
//            [kDefaults setObject:@"" forKey:@"token"];
//            [kDefaults setObject:@"" forKey:@"loginId"];
//            [kDefaults setObject:@"" forKey:@"password"];
//            [kDefaults synchronize];
            UserInfo * userInfo = [UserInfo sharedUserInfo];
            [userInfo mj_setKeyValues:base.data];
            [UserInfo sharedUserInfo].bIsLogin = NO;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [LCProgressHUD hide];
                //跳转到登录页面
                YQLoginVC* loginVC=[YQLoginVC new];
                GFNavigationController * loginNav = [[GFNavigationController alloc] initWithRootViewController:loginVC];
                TheApp.keyWindow.rootViewController =loginNav;
            });
            
        }
    } failureBlock:^(NSError *error) {
        
    }];
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArr[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  FIT(60);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return FIT(15);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return FIT(170);
    }
    return 0.001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GSPersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:GSPersonInfoCellReuseIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell= [[GSPersonInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GSPersonInfoCellReuseIdentifier];
    }

    cell.imageView.image=[UIImage imageNamed:self.imagesArr[indexPath.section][indexPath.row]];
    cell.titleLab.text=self.dataArr[indexPath.section][indexPath.row];
    cell.titleLab.font=[UIFont systemFontOfSize:FIT(17)];
    cell.titleLab.textColor=UIColorFromRGB(0X333333);

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor clearColor];
    [backView addSubview:self.loginOutBtn];
    [self.loginOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-FIT(45));
        make.height.mas_equalTo(FIT(56));
    }];
    return backView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //我的钱包
            if (KUserSingleton.bIsLogin == YES) {
                if ([self.anthStatus integerValue] == 3) {
                    YQ_PUSH([YQMyWalletVC new]);
                }else {
                    [LCProgressHUD showMessage:@"您还未进行身份认证，请先认证"];
                }
            }else {
                YQLoginVC* loginVC = [[YQLoginVC alloc]init];
                GFNavigationController * loginNav = [[GFNavigationController alloc] initWithRootViewController:loginVC];
                [self presentViewController:loginNav animated:YES completion:^{
                    
                }];
            }
            
            
        }else {
            //我的通证
            if (KUserSingleton.bIsLogin == YES) {
                if ([self.anthStatus integerValue] == 3) {
                    YQ_PUSH([YQMyPassCardVC new]);
                }else {
                    [LCProgressHUD showMessage:@"您还未进行身份认证，请先认证"];
                }
            }else {
                YQLoginVC* loginVC = [[YQLoginVC alloc]init];
                GFNavigationController * loginNav = [[GFNavigationController alloc] initWithRootViewController:loginVC];
                [self presentViewController:loginNav animated:YES completion:^{
                    
                }];
            }
            
            
        }
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            YQ_PUSH([YQSystemAnnounceVC new]);
        }else if (indexPath.row == 1) {
            YQ_PUSH([AboutUsCtl new]);
        }
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
